﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Linq;
using System.Drawing;

namespace Dracham.MapEditor.Textures
{
    public class TextureManager
    {
        private XmlDocument xTextures;
        public List<Texture> Textures {get;set;}
        private String filePath;

        public TextureManager(String appPath)
        {
            this.filePath = appPath + "Textures.xml";
            xTextures = new XmlDocument();

            if (!File.Exists(this.filePath))
            {
                File.WriteAllText(this.filePath, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<Textures></Textures>");
            }

            xTextures.Load(this.filePath);
            LoadTextures();
        }

        private void LoadTextures()
        {
            Textures = new List<Texture>();

            foreach (XmlNode node in xTextures.GetElementsByTagName("Texture"))
            {
                Boolean useTranparency = Convert.ToBoolean(node.Attributes["UseTransparency"].Value);
                Color color = Color.FromArgb(Convert.ToInt32(node.Attributes["Color"].Value));

                Textures.Add(new Texture(node.Attributes["Name"].Value, Convert.FromBase64String(node.FirstChild.Value), useTranparency, color));
            }
        }

        private void SaveXml()
        {
            xTextures.Save(this.filePath);
        }

        private XmlAttribute CreateAttribute(String name, String value)
        {
            XmlAttribute attrib = xTextures.CreateAttribute(name);
            attrib.Value = value;

            return attrib;
        }

        public Texture ImportTexture(String path, Boolean useTransparency, Color color)
        {
            String textureName = Path.GetFileNameWithoutExtension(path);
            Byte[] imageBytes = File.ReadAllBytes(path);

            XmlNode textureNode = xTextures.CreateElement("Texture");
            textureNode.AppendChild(xTextures.CreateCDataSection(Convert.ToBase64String(imageBytes)));

            textureNode.Attributes.Append(CreateAttribute("Name", textureName));
            textureNode.Attributes.Append(CreateAttribute("UseTransparency", useTransparency.ToString()));
            textureNode.Attributes.Append(CreateAttribute("Color", color.ToArgb().ToString()));
            xTextures.GetElementsByTagName("Textures")[0].AppendChild(textureNode);

            //
            // save textures
            SaveXml();

            Textures.Add(new Texture(textureName, imageBytes, useTransparency, color));
            return Textures.Last();
        }

        public Texture GetTexture(String name)
        {
            return Textures.Where(t => t.Name == name).SingleOrDefault();
        }

        public XmlDocument GetXmlDocument()
        {
            return this.xTextures;
        }
    }
}
